﻿using MapleLeaf.Core.Serilog;

namespace DiLe.Mes.Local.Middleware {
    /// <summary>
    /// 
    /// </summary>
    public class RequestLoggingMiddleware {
        private readonly RequestDelegate _next;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        public RequestLoggingMiddleware(RequestDelegate next) {
            _next = next;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context) {
            // 记录请求方法和路径
            string url = context.Request.Path;
            var requestMessage = $"{context.Request.Method} {url}";
            if (url.Contains("upload", StringComparison.CurrentCultureIgnoreCase)) {
                await _next(context);
            } else if (url.Contains("QueryAlarm", StringComparison.CurrentCultureIgnoreCase)) {
                await _next(context);
            } else {
                // 处理POST请求参数
                if (context.Request.Method == "POST") {
                    context.Request.EnableBuffering();
                    var requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
                    context.Request.Body.Position = 0;
                    requestMessage += $", Body: {requestBody}";
                } else if (context.Request.Method == "GET") {
                    // 处理请求参数
                    var requestParameters = context.Request.QueryString.ToString();
                    requestMessage += $", Parameter: {requestParameters}";
                }
                // 处理请求前记录日志
                SerilogLogHelper.WriteInterfaceLog($"Request: {requestMessage}");


                // 执行下一个中间件或处理程序，并获取返回值
                using var memoryStream = new MemoryStream();
                var originalResponseBody = context.Response.Body;
                context.Response.Body = memoryStream;

                await _next(context);
                // 获取响应的返回值
                memoryStream.Seek(0, SeekOrigin.Begin);
                var responseBody = await new StreamReader(memoryStream).ReadToEndAsync();

                // 记录返回值
                if (context.Response.StatusCode != 200) {
                    SerilogLogHelper.WriteInterfaceLog($"url{context.Request.Path} ,Response: {context.Response.StatusCode}, Body: {responseBody}");
                }
                memoryStream.Seek(0, SeekOrigin.Begin);
                await memoryStream.CopyToAsync(originalResponseBody);
                context.Response.Body = originalResponseBody;

            }

        }
    }
}
